//
//  WQEmojiKeyBoard.swift
//  WQEmojiKeyboard-swift
//
//  Created by Xiang on 2021/5/21.
//

import Foundation
import UIKit

protocol WQEmojiKeyBoardDelegate : NSObjectProtocol {
    func emojiKeyBoard(emojiKeyBoard: WQEmojiKeyBoard, emojiBtnClickForIndex: Int, value:String, img:String)
}


class WQEmojiKeyBoard: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    
    weak var delegate : WQEmojiKeyBoardDelegate?
    
    var attTextColor : UIColor = UIColor.lightGray
    
    var attTextFont : UIFont = UIFont.systemFont(ofSize: 16)
    
    private var collectionView : UICollectionView?
    
    private var textView : UITextView?
    
    private var emojiDic :[String:String] = [String:String]()
    
    private var emojiImgArray : Array<Any>!
    
    private var location : Int = 0
    
    init(frame : CGRect,textView : UITextView) {
        super.init(frame: frame)
        self.textView = textView
        initData()
        initUI()
    }
    
    private func initUI() {
    
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        let width : CGFloat = (self.frame.width-20-35)/8
        let height : CGFloat = width
        layout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 15, right: 10)
        layout.itemSize = CGSize.init(width: width, height: height)
        
        collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: 250), collectionViewLayout: layout)
        collectionView!.backgroundColor = UIColor.white
        collectionView!.delegate = self
        collectionView!.dataSource = self
        collectionView!.layer.zPosition = 1
        collectionView!.register(WQEmojiItemCell.self, forCellWithReuseIdentifier: "WQEmojiItemCell")
        self.addSubview(collectionView!)
    }
    
    
    func keyBoardFrameChaneWithFrame(frame : CGRect) {
        collectionView?.frame = CGRect.init(x: 0, y: 0, width:frame.width, height: frame.height)
    }
    

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//MARK: 初始化数据
extension WQEmojiKeyBoard{
    
    private func initData() {
        let pathStr:String = Bundle.main.path(forResource: "emoji", ofType: "json") ?? ""
    
        var emojiData : Data?
        do {
            emojiData = try Data.init(contentsOf: URL.init(fileURLWithPath: pathStr))
        } catch {
        }
    
        var classArray = [Any]()
        do {
            classArray = try JSONSerialization.jsonObject(with: emojiData!, options: .allowFragments) as! [Any]
        } catch {
        }
        
        self.emojiImgArray = classArray
        
        for i in 0..<self.emojiImgArray!.count {
            let dict : Dictionary = self.emojiImgArray![i] as! Dictionary<String, Any>
            let vall = dict["img"]
            let key = dict["value"]
            self.emojiDic[key as! String] = vall as? String
        }

        //print(self.emojiDic)
        //print(self.emojiImgArray)
    }
    
}

//MARK: collectionView delegate
extension WQEmojiKeyBoard{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.emojiImgArray?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WQEmojiItemCell", for: indexPath) as! WQEmojiItemCell
        let dict : Dictionary = self.emojiImgArray![indexPath.row] as! Dictionary<String, Any>
        let imgNameStr : String = dict["img"] as! String
        cell.iconIv.image = UIImage.init(named: imgNameStr)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let dict : Dictionary = self.emojiImgArray![indexPath.row] as! Dictionary<String, Any>
        
        let value : String = dict["value"] as! String
        let img : String = dict["img"] as! String
        
        var faceString : String = self.textView?.text ?? ""
        faceString.append(value)
        
        let emotionTextAttachment = EmotionTextAttachment()
        emotionTextAttachment.bounds = CGRect.init(x: 0, y: -5.5, width: 21, height: 21)
        emotionTextAttachment.emotionStr = value
        emotionTextAttachment.image = UIImage.init(named: img)
        self.location = self.textView?.selectedRange.location ?? 0
        
        let attri = NSAttributedString(attachment: emotionTextAttachment)
        self.textView?.textStorage.insert(attri, at: self.textView?.selectedRange.location ?? 0)
        
        self.textView?.textStorage.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.darkGray, range: NSRange.init(location: 0, length: self.textView!.text.count))
        self.textView?.textStorage.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: NSRange.init(location: 0, length: self.textView!.text.count))
        self.textView?.selectedRange = NSRange.init(location: self.location+1, length: 0)
    
        if delegate != nil {
            self.delegate!.emojiKeyBoard(emojiKeyBoard: self, emojiBtnClickForIndex: indexPath.row, value: value, img: img)
        }
        
    }
}



class WQEmojiItemCell: UICollectionViewCell {
    
    var iconIv : UIImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(iconIv)
        iconIv.frame = CGRect.init(x: 5, y: 5, width: frame.width-10, height: frame.height-10)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

